package com.ailanyin.security.config;

import com.ailanyin.security.filter.JwtAuthenticationTokenFilter;
import com.ailanyin.security.filter.RateLimitFilter;
import com.ailanyin.security.filter.XssFilter;
import com.ailanyin.security.handle.LogoutHandler;
import com.ailanyin.security.handle.NoTokenResult;
import com.ailanyin.security.service.SecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/21 0021 下午 14:06
 */

public class BaseSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private NoTokenResult noTokenResult;
    @Autowired
    private LogoutHandler logoutHandler;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // 由于使用的是JWT，我们这里不需要csrf
        httpSecurity.csrf()
                .disable()
                //添加自定义未授权和未登录结果返回
                .exceptionHandling()
                .authenticationEntryPoint(noTokenResult)
                .and()
                // 基于token，所以不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 白名单路径
                .antMatchers("/",
                        "/*.*",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-resources/**",
                        "/v2/api-docs/**",
                        "/druid/**",
                        "/file/**",
                        "/login",
                        "/register",
                        "/captchaImage",
                        "/getRouters"
                )
                .permitAll()
                //跨域请求会先进行一次options请求
                .antMatchers(HttpMethod.OPTIONS)
                .permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest()
                .authenticated();
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 退出处理
        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutHandler);
        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public NoTokenResult noTokenResult() {
        return new NoTokenResult();
    }

    @Bean
    public SecurityUserService securityUserService() {
        return new SecurityUserService();
    }

    @Bean
    public XssFilter xssFilter() {
        return new XssFilter();
    }

    @Bean
    public LogoutHandler logoutHandler() {
        return new LogoutHandler();
    }

    @Bean
    public RateLimitFilter rateLimitFilter() {
        return new RateLimitFilter();
    }
}
